package com.qy127.controller;

import com.qy127.dao.MenuDao;
import com.qy127.entity.Menu;
import com.qy127.entity.Staff;
import com.qy127.entity.Tree;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @ClassName MenuController
 * @Description ToDo
 * @Auther teacher Bai
 * @Date 2020/12/26 11:10
 */
@RestController
@RequestMapping("/menu")
public class MenuController {
    @Autowired
    private MenuDao menuDao;

    /**
     * 根据rid查询对应的菜单信息，填充左侧导航菜单
     * @param request
     * @return
     */
    @RequestMapping("/getAllMenuByRId")
    public ModelAndView getAllMenuByRId(HttpServletRequest request){
        Staff staff = (Staff) request.getSession().getAttribute("staff");
        List<Menu> menus = menuDao.getAllMenuByRid(staff.getRoleId());
        //System.out.println("aaaaa"+menus);
        ModelAndView mv = new ModelAndView();
        mv.addObject("menus",menus);
        mv.setViewName("homePage");
        return mv;
    }

    /**
     * 先查询出所有的权限菜单信息
     */
    @RequestMapping("/getAllMenu")
    public List<Tree> getAllMenu(){
        List<Tree> menus = menuDao.getAllMenu();
        //System.out.println(menus);
        return menus;
    }

    /**
     * 根据rid查询到当前角色对应的所有子菜单mid并且存储入一个数组中，返回前台
     * @param rid
     * @return
     */
    @RequestMapping("/getAllMidByRid")
    public List getAllMidByRid(String rid){
        List<Map<String, Object>> maps = menuDao.getAllMidByRid(rid);
        List<Object> list = new ArrayList<>();
        //将得到的List<Map>数据储存到list中
        for (Map<String, Object> map : maps) {
            list.add(map.get("mid"));
        }
        //System.out.println(list);
        return list;
    }


    @RequestMapping("/updateMenuByRid")
    public Map updateMenuByRid(String rid ,String checkArr){
        String[] split = checkArr.split(",");
        //System.out.println(Arrays.toString(split));
        //1.先将权限和角色中间表中的所有跟当前rid对应的记录都干掉
        menuDao.delRolePremissionByRid(rid);
        //2.在将传来的数组中的所有mid 再重新插入到权限和角色中间表中
        menuDao.insertRolePremission(rid,split);
        HashMap<Object, Object> map = new HashMap<>();
        map.put("code","200");
        map.put("msg","修改成功");
        return map;
    }


}
